package com.mimc.controller.api;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.jfinal.aop.Inject;
import com.mimc.common.constant.CacheConstants;
import com.mimc.common.constant.EventConstants;
import com.mimc.core.model.ImUser;
import com.mimc.core.model.SysAppVersion;
import com.mimc.core.service.ImUserService;
import com.mimc.core.service.SysAppVersionService;
import com.mimc.framework.domain.AjaxResult;
import com.mimc.framework.domain.KV;
import com.mimc.framework.jwt.ApiTokenUtils;
import com.mimc.framework.utils.TranslateUtil;
import com.mimc.service.ShSysConfigService;
import com.mimc.service.ShTranslateService;
import io.jboot.Jboot;
import io.jboot.db.model.Columns;
import io.jboot.utils.CacheUtil;
import io.jboot.utils.StrUtil;
import io.jboot.web.controller.JbootController;
import io.jboot.web.controller.annotation.RequestMapping;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RequestMapping("/api/index")
public class IndexController extends JbootController {
    @Inject
    private ShSysConfigService shSysConfigService;
    @Inject
    private ShTranslateService shTranslateService;
    @Inject
    private ImUserService imUserService;
    @Inject
    private SysAppVersionService sysAppVersionService;
    /**
     * 获取APP配置
     * @return
     */
    public AjaxResult getConfig(){
        //String lang=getPara("lang","zh");
        Map<String,Object> configMap=new HashMap<>();
        configMap.put("langVersion",shSysConfigService.getConfigValueByKey("lang.version"));
        configMap.put("langList",shTranslateService.getLangListByCache());
        //configMap.put("translateList",shTranslateService.getTranslateByLangName(lang));
        configMap.put("home",TranslateUtil.translate("首页"));
        configMap.put("avatar",shSysConfigService.getConfigValueByKey("default.avatar.url"));
        return AjaxResult.success("",configMap);
    }

    /**
     * 获取翻译
     * @return
     */
    public AjaxResult getTranslates(){
        String lang=getPara("lang","en");
        List<KV> list=shTranslateService.getTranslateByLangName(lang);
        return AjaxResult.success("",list);
    }

    /**
     * 发送邮件验证码
     * @return
     */
    public AjaxResult sendMailCode(){
        String email=getPara("email");
        boolean isEmail = Validator.isEmail(email);
        if(!isEmail){
            return AjaxResult.error(TranslateUtil.translate("请输入正确的邮箱"));
        }
        int code = RandomUtil.randomInt(1000, 9999);
        String content=String.format(shSysConfigService.getConfigValueByKey("sms.code.template"),code);
        Map<String,Object> map=new HashMap<>();
        map.put("email",email);
        map.put("content",content);
        map.put("title","登录验证码");
        Jboot.sendEvent(EventConstants.SENDEMAILEVENT,map);
        CacheUtil.put(CacheConstants.EMAIL_CODE,email,code,CacheConstants.EMAIL_CODE_LIVETIME);
        log.info("邮件验证码：{}",code);
        return AjaxResult.success(TranslateUtil.translate("发送成功")).put("code1",code);
    }

    /**
     * 邮箱验证码登录
     * @return
     */
    public AjaxResult loginByCode(){
        String email=getPara("email");
        Integer code=getInt("code",0);
        boolean isEmail = Validator.isEmail(email);
        if(!isEmail){
            return AjaxResult.error(TranslateUtil.translate("请输入正确的邮箱"));
        }
        if(code==0){
            return AjaxResult.error(TranslateUtil.translate("请输入4位的验证码"));
        }
        Integer cacheCode =CacheUtil.get(CacheConstants.EMAIL_CODE,email);
        if(cacheCode==null){
            return AjaxResult.error(TranslateUtil.translate("验证码过期"));
        }
        if(cacheCode.intValue()!=code.intValue()){
            return AjaxResult.error(TranslateUtil.translate("验证码错误"));
        }
        ImUser user=imUserService.findFirstByColumns(Columns.create("email",email));
        if(user==null){
            //创建用户
            user=new ImUser();
            user.setEmail(email);
            user.setNickname(email);
            user.setCreatedTime(new Date());
            user.setUpdatedTime(new Date());
            Long userId= (Long) imUserService.save(user);
            user.setUserId(userId);
        }
        //生成token
        String key= Jboot.configValue("yminfo.jwtkey");
        String expireTime= Jboot.configValue("yminfo.jwtExpireTime");
        String token= ApiTokenUtils.genToken(user.getUserId(),key, Integer.valueOf(expireTime));
        return AjaxResult.success(TranslateUtil.translate("登录成功"),token);
    }

    /**
     * versionCode传这个参数是为了解决部分用户app长期不使用，第一次打开服务器查到的版本是最新的是wgt包，
     * 但是之前app有过整包更新，如果直接更新最新wgt的话，会出现以前的整包添加的原生模块或者安卓权限无法使用，
     * 所以后端查询版本必须返回大于当前versionCode版本的最新的整包apk地址或者是应用市场地址，
     * 如果没有大于versionCode的整包，就返回最新的wgt包地址就行。
     * @return
     */
    public AjaxResult checkUpdate(){
        String platform=getPara("platform");
        String versionName=getPara("versionName");
        Integer versionCode=getInt("versionCode",0);
        //先检查整包升级
        SysAppVersion appVersion=sysAppVersionService.findFirstByColumns(Columns.create("platform",platform).eq("package_type",0),"version_id desc");
        if(appVersion!=null){
            Integer versionCodeLast=Integer.parseInt(appVersion.getVersionCode());
            if(versionCode<versionCodeLast){
                //返回更新
                Map<String,Object> data=new HashMap<>();
                data.put("platform",appVersion.getPlatform());
                data.put("content",appVersion.get(ApiTokenUtils.getLang()));
                data.put("versionName",appVersion.getVersionName());
                data.put("versionCode",appVersion.getVersionCode());
                data.put("downloadUrl",appVersion.getDownloadUrl());
                data.put("packageType",appVersion.getPackageType());
                data.put("force",appVersion.getForce());
                data.put("silence",appVersion.getSilence());
                data.put("issue",appVersion.getIssue());
                return AjaxResult.success("有更新",data);
            }else{
                SysAppVersion wgtAppVersion=sysAppVersionService.findFirstByColumns(Columns.create("platform",platform)
                        .eq("package_type",1),"id desc");
                if(wgtAppVersion!=null){
                    //返回更新
                    Map<String,Object> data=new HashMap<>();
                    data.put("platform",appVersion.getPlatform());
                    data.put("content",appVersion.get(ApiTokenUtils.getLang()));
                    data.put("versionName",appVersion.getVersionName());
                    data.put("versionCode",appVersion.getVersionCode());
                    data.put("downloadUrl",appVersion.getDownloadUrl());
                    data.put("packageType",appVersion.getPackageType());
                    data.put("force",appVersion.getForce());
                    data.put("silence",appVersion.getSilence());
                    data.put("issue",appVersion.getIssue());
                    return AjaxResult.success("有更新",data);
                }else{
                    return AjaxResult.error("没有更新");
                }
            }
        }else{
            SysAppVersion wgtAppVersion=sysAppVersionService.findFirstByColumns(Columns.create("platform",platform)
                    .eq("package_type",1),"id desc");
            if(wgtAppVersion!=null){
                //返回更新
                Map<String,Object> data=new HashMap<>();
                data.put("platform",appVersion.getPlatform());
                data.put("content",appVersion.get(ApiTokenUtils.getLang()));
                data.put("versionName",appVersion.getVersionName());
                data.put("versionCode",appVersion.getVersionCode());
                data.put("downloadUrl",appVersion.getDownloadUrl());
                data.put("packageType",appVersion.getPackageType());
                data.put("force",appVersion.getForce());
                data.put("silence",appVersion.getSilence());
                data.put("issue",appVersion.getIssue());
                return AjaxResult.success("有更新",data);
            }else{
                return AjaxResult.error("没有更新");
            }
        }
    }

    /**
     * 邮箱注册
     * @return
     */
    public AjaxResult register(){
        String email=getPara("email");
        Integer code=getInt("code",0);
        String password=getPara("password");
        boolean isEmail = Validator.isEmail(email);
        if(!isEmail){
            return AjaxResult.error(TranslateUtil.translate("请输入正确的邮箱"));
        }
        if(code==0){
            return AjaxResult.error(TranslateUtil.translate("请输入4位的验证码"));
        }
        if(StrUtil.isBlank(password)){
            return AjaxResult.error(TranslateUtil.translate("请输入密码"));
        }
        if(password.length()<6){
            return AjaxResult.error(TranslateUtil.translate("密码长度需大于等于6"));
        }
        Integer cacheCode =CacheUtil.get(CacheConstants.EMAIL_CODE,email);
        if(cacheCode==null){
            return AjaxResult.error(TranslateUtil.translate("验证码过期"));
        }
        log.info("cacheCode:{},code:{}",cacheCode,code);
        if(cacheCode.intValue()!=code.intValue()){
            return AjaxResult.error(TranslateUtil.translate("验证码错误"));
        }
        ImUser user=imUserService.findFirstByColumns(Columns.create("email",email));
        if(user!=null){
            return AjaxResult.error(TranslateUtil.translate("该邮箱已注册，请使用其他邮箱注册"));
        }
        //创建用户
        user=new ImUser();
        user.setEmail(email);
        user.setNickname(email);
        user.setPassword(SecureUtil.md5(password));
        user.setCreatedTime(new Date());
        user.setUpdatedTime(new Date());
        imUserService.save(user);
        return AjaxResult.success(TranslateUtil.translate("注册成功"));
    }

    /**
     * 邮箱密码登录
     * @return
     */
    public AjaxResult login(){
        String email=getPara("email");
        String password=getPara("password");
        boolean isEmail = Validator.isEmail(email);
        if(!isEmail){
            return AjaxResult.error(TranslateUtil.translate("请输入正确的邮箱"));
        }
        if(StrUtil.isBlank(password)){
            return AjaxResult.error(TranslateUtil.translate("请输入密码"));
        }
        if(password.length()<6){
            return AjaxResult.error(TranslateUtil.translate("密码长度需大于等于6"));
        }
        ImUser user=imUserService.findFirstByColumns(Columns.create("email",email));
        if(user==null){
            return AjaxResult.error(TranslateUtil.translate("该用户不存在，请注册"));
        }
        if(!SecureUtil.md5(password).equals(user.getPassword())){
            return AjaxResult.error(TranslateUtil.translate("密码错误"));
        }
        //生成token
        String key= Jboot.configValue("yminfo.jwtkey");
        String expireTime= Jboot.configValue("yminfo.jwtExpireTime");
        String token= ApiTokenUtils.genToken(user.getUserId(),key, Integer.valueOf(expireTime));
        return AjaxResult.success(TranslateUtil.translate("登录成功"),token);
    }

    /**
     * 找回密码
     * @return
     */
    public AjaxResult forget(){
        String email=getPara("email");
        Integer code=getInt("code",0);
        String password=getPara("password");
        boolean isEmail = Validator.isEmail(email);
        if(!isEmail){
            return AjaxResult.error(TranslateUtil.translate("请输入正确的邮箱"));
        }
        if(code==0){
            return AjaxResult.error(TranslateUtil.translate("请输入4位的验证码"));
        }
        if(StrUtil.isBlank(password)){
            return AjaxResult.error(TranslateUtil.translate("请输入密码"));
        }
        if(password.length()<6){
            return AjaxResult.error(TranslateUtil.translate("密码长度需大于等于6"));
        }
        Integer cacheCode =CacheUtil.get(CacheConstants.EMAIL_CODE,email);
        if(cacheCode==null){
            return AjaxResult.error(TranslateUtil.translate("验证码过期"));
        }
        if(cacheCode.intValue()!=code.intValue()){
            return AjaxResult.error(TranslateUtil.translate("验证码错误"));
        }
        ImUser user=imUserService.findFirstByColumns(Columns.create("email",email));
        if(user==null){
            return AjaxResult.error(TranslateUtil.translate("该邮箱未注册"));
        }
        user.setPassword(SecureUtil.md5(password));
        user.setUpdatedTime(new Date());
        imUserService.update(user);
        return AjaxResult.success(TranslateUtil.translate("找回成功"));
    }
}
